package com.baymax.test.scene.internal

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import kotlin.math.max

class ViewIndicator : View {

    var dotRadius = 5f
    var dotGap = 10f
    var totalSize = 0

    private val selectColor = Color.argb(255, 0xf2, 0xfa, 0xff)
    private val normalColor = Color.argb(0x7f, 0xf2, 0xfa, 0xff)

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
     var selectIndex = 0
         set(value) {
            val old = field
            field = value % max(1, totalSize)
            if (old != field) {
                invalidate()
            }
        }

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthModel = MeasureSpec.getMode(widthMeasureSpec)
        val heightModel = MeasureSpec.getMode(heightMeasureSpec)
        val width: Int = if (widthModel == MeasureSpec.EXACTLY) {
            MeasureSpec.getSize(widthMeasureSpec)
        } else {
            (dotRadius * 2 * totalSize + (totalSize - 1) * dotGap + paddingLeft + paddingRight).toInt()
        }

        val height = if (heightModel == MeasureSpec.EXACTLY) {
            MeasureSpec.getSize(heightMeasureSpec)
        } else {
            (dotRadius * 2).toInt() + paddingTop + paddingBottom
        }
        setMeasuredDimension(width, height)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        var x = paddingLeft.toFloat()
        var y = height / 2f
        for (i in 0 until totalSize) {
            if (selectIndex == i) {
                paint.color = selectColor
            } else {
                paint.color = normalColor
            }
            x += dotRadius
            if (i > 0) {
                x += dotGap + dotRadius
            }
            canvas.drawCircle(x, y, dotRadius, paint)
        }
    }


    /**
     * 指向下一个
     */
    fun next() {
        selectIndex += 1
    }


}